import { reqcatelist, reqspecscount, reqspecslist } from "../../request/api"
const state = {
    //初始值
    list: [],
    //总数
    count: 0,
    //一页的数量
    size: 2,
    //页码
    page: 1
}

const getters = {
    //导出给组件
    list(state) {
        return state.list
    },
    //导出给组件
    count(state) {
        return state.count
    },
    //导出给组件
    size(state) {
        return state.size
    },
}

const mutations = {
    //修改list
    changeList(state, list) {
        state.list = list;
    },
    //修改count
    changeCount(state, count) {
        state.count = count
    },
    //修改page
    changePage(state, page) {
        state.page = page
    }
}

const actions = {
    //请求
    reqList({ commit, dispatch, state: { size, page } },isAll=false) {
        let params=isAll?{}:{
            page,
            size
        }
        reqspecslist(params).then(res => {
            if (res.data.code == 200) {
                //修改list
                let list = res.data.list ? res.data.list : [];

                //如果取回来了空数组，并且不是第一页，那么就请上一页的数据
                if (list.length == 0 && page !== 1) {
                    commit("changePage", page - 1)
                    dispatch("reqList");
                    return;
                }
                commit("changeList", list)

            }
        })
    },
    //请求总数
    reqCount({ commit }) {
        reqspecscount().then(res => {
            if (res.data.code == 200) {
                //修改总数
                commit("changeCount", res.data.list[0].total)
            }
        })
    },
    //页面触发修改page
    changePage({ commit, dispatch }, page) {
        //修改页码
        commit("changePage", page)
        //触发请求list
        dispatch("reqList")

    }
}


export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}